let pathCond = getUrlParamToObj();
let channelId;
let roleType;
let token = pathCond.token || '';
let type = pathCond.type || 2;// 1=文本机器人，2=语音机器人
var path_video = path;

var audioContext = new(window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window
    .msAudioContext)();
var socket;
var recorder;
var kongvoice;
var cnt = 0;
var sendempty = false;
init();

function init() {
    EasyAjax.post_json({
        url: path_video + 'robotRecord/init/auth',
        timeout: '60000',
        data: JSON.stringify({
            token : token,
            type : type    
        }),
    }, function(data) {
        startRecording();
        console.log(data);
        var data = data.data;
        var obj = new Object();
        obj.channelId = data.channelId;
        obj.roleType = data.roleType;
        openChannel(obj);
    });
}
var heartCheck = {
    timeout: 3000,
    timeoutObj: null,
    serverTimeoutObj: null,
    start: function() {
        var self = this;
        this.timeoutObj && clearTimeout(this.timeoutObj);
        this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
        this.timeoutObj = setTimeout(function() {
            //这里发送一个心跳，后端收到后，返回一个心跳消息，
            socket.send("地瓜地瓜我是土豆，听到请回答！！！");
        }, this.timeout)
    }
}

var index_lay;


// 打开websocket
function openChannel(obj) {
    var wssurl = WS_SOCKET;
    var url = wssurl + 'audioMessage/' + obj.channelId + "/" + obj.roleType;
    console.log("url=" + url);
    socket = new WebSocket(url);
    socket.onopen = onChannelOpened;
    socket.onmessage = onChannelMessage;
    socket.onclose = onChannelClosed;
    socket.onerror = onChannelError;
}
// websocket打开
function onChannelOpened() {
    heartCheck.start();
    setTimeout(sendVoice, 5000);
}

var theTime = 0;
// websocket收到消息
function onChannelMessage(msg) {
    var data = msg.data;
    var datalen = msg.data.size;
    heartCheck.start();
    if (msg.data instanceof Blob) { // 处理二进制信息
        var reader = new FileReader();
        reader.onload = function(evt) {
            if (evt.target.readyState == FileReader.DONE) {
                var data = new Uint8Array(evt.target.result);
                audioContext.decodeAudioData(evt.target.result, function(buffer) {
                    //解码成pcm流
                    var audioBufferSouceNode = audioContext.createBufferSource();
                    audioBufferSouceNode.buffer = buffer;
                    audioBufferSouceNode.connect(audioContext.destination);
                    audioBufferSouceNode.start(0);

                }, function(e) {
                    // alert("Fail to decode the file.");
                });
            }
        }
        reader.readAsArrayBuffer(data);
    } else {
        if (data.indexOf("stop") != -1) { //处理文本
            //停止录音  停止发送数据 
            sendempty = true;
            setTimeout(sendkongvoice, 220);
            var time = ((data.split("-")[1]) * 1000) - 1000;
            // var time = ((data.split("-")[1]*8)/(8*1000*24*1))*1000
            console.log('音频时长: ' + time);
            $(".flag").html('机器人开始说话');
            setTimeout(sleep, time);
        }
        if (data.indexOf("finish") != -1) { //处理文本
            //停止录音  停止发送数据
            stopRecording();
            setTimeout(finishRecording, 3000);
        }
    }
}
    // websocket异常
function onChannelError() {
    console.log("WebSocket连接发生错误");
}
// websocket关闭
function onChannelClosed(e) {
    console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean)
    if (e.code != 1000) {
        alert('网络环境差,请调整网络后重试！')
        location.reload();
    }
}
// 发送信息
function sendMessage(message) {
    socket.send(message);
}

function sleep() {
    sendempty = false;
    socket.send("on");
    $(".flag").html('用户开始说话');
    setTimeout(sendVoice, 150);
}


function startRecording() {
    HZRecorder.get(function(rec) {
        recorder = rec;
        recorder.start();
    });
}

function stopRecording() {
    recorder.stop();
}

function finishRecording() {
    $("#videoStartRecord").click();
}

function sendkongvoice() {
    if (sendempty == true) {
        socket.send(kongvoice);
        setTimeout(sendkongvoice, 180);
    }
}

function sendVoice() {
        if (typeof(recorder) != "undefined" && recorder != null) {
            var file = recorder.getBlob();
            if (cnt == 2) {
                kongvoice = file;
            }
            if (kongvoice != "undefined") {
                socket.send(file);
                cnt++;
            }
        }
        setTimeout(sendVoice, 150);
        return true;
}

// 关闭窗口退出
window.onbeforeunload = function() {
    sendMessage("off");
    socket.close();
}

$(function() {
    $('body').on('touchstart', '.queding', function() {
        layer.closeAll();
    })
})

navigator.getUserMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia ||
    navigator.msGetUserMedia);